<template>
  <div class="tab_content">
    <!-- 操作按钮区域 -->
    <div class="common_button flex_ac margin_t20">
      <div class="right_button flex">
        <a href="javascript:;" class="color_blue" @click="handleAdd">
          <img class="btn_img" src="@/assets/pinggu/add.png" alt="">新建
        </a>
      </div>
    </div>
    
    <!-- 数据表格 -->
    <div class="common_block_div">
      <el-table v-loading="loading" :data="categoryList" style="width: 100%">
        <el-table-column label="集合编号" prop="id" width="80" />
        <el-table-column label="类别名称" prop="title" :show-overflow-tooltip="true" />
        <el-table-column label="排序" prop="sort" sortable width="100" />
        <el-table-column label="更新时间" prop="update_time" width="180" />
        <el-table-column label="操作" align="center" width="200px" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="text" style="color: #F56C6C;" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="categoryListTotal > 0" :total="categoryListTotal" :page.sync="queryParams.page"
        :limit.sync="queryParams.limit" @pagination="getCategoryList" />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-dialogDrag :close-on-click-modal="false" :title="dialogTitle" :visible.sync="dialogVisible"
      width="500px" append-to-body @closed="handleDialogClosed">
      <el-form ref="dialogForm" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="类别名称" prop="title">
              <el-input v-model="form.title" clearable placeholder="请输入类别名称" maxlength="50" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" :min="0" :max="9999" placeholder="请输入排序值" style="width: 100%" />
              <div class="form-hint">数字越小越靠前，默认为0</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="is_ajax">{{ is_ajax ? '保存中···' : '确定' }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination/index.vue";
// 导入采集管理API
import collectionApi from "@/api/collection";

export default {
  name: 'CollectCategory',
  components: {
    Pagination
  },
  props: {
    projectId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      categoryList: [],
      categoryListTotal: 0,
      queryParams: {
        page: 1,
        limit: 16,
        project_id: '' // 项目ID，用于筛选该项目的采集类别
      },
      dialogVisible: false,
      dialogTitle: '新建类别',
      is_ajax: false,
      form: {
        id: '',
        title: '',
        project_id: '', // 项目ID
        sort: 0 // 排序，默认为0
      },
      rules: {
        title: [
          { required: true, message: "类别名称不能为空", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "排序值不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    // 如果有项目ID，设置查询参数
    if (this.projectId) {
      this.queryParams.project_id = this.projectId;
      this.form.project_id = this.projectId;
    }
    this.getCategoryList();
  },
  watch: {
    projectId(newVal) {
      // 当项目ID变化时，更新查询参数
      if (newVal) {
        this.queryParams.project_id = newVal;
        this.form.project_id = newVal;
        this.getCategoryList();
      }
    }
  },
  methods: {
    /** 获取采集类别列表 */
    getCategoryList() {
      const _this = this;
      this.loading = true;
      
      // 构建查询参数
      const params = {
        ...this.queryParams
      };
      
      // 如果有项目ID，添加到查询参数中
      if (this.projectId) {
        params.project_id = this.projectId;
      }
      
      // 调用API获取采集类别列表
      collectionApi.categoryList(params).then(function (res) {
        if (res && res.message) {
          _this.categoryList = res.message.data || res.message || [];
          _this.categoryListTotal = res.message.total || _this.categoryList.length || 0;
        }
        _this.loading = false;
      }).catch(function (error) {
        console.error('获取采集类别列表失败:', error);
        _this.loading = false;
        // 如果接口失败，可以显示错误提示
        // _this.$message.error('获取采集类别列表失败');
      });
    },

    /** 新增类别 */
    handleAdd() {
      this.dialogTitle = '新建类别';
      this.resetForm();
      this.form = {
        id: '',
        title: '',
        project_id: this.projectId || '',
        sort: 0
      };
      this.dialogVisible = true;
    },

    /** 编辑类别 */
    handleEdit(row) {
      const _this = this;
      if (!row.id) {
        this.$message.warning('无法编辑该数据');
        return;
      }
      
      this.dialogTitle = '编辑类别';
      this.resetForm();
      
      // 如果有详情接口，可以调用获取完整信息
      // 否则直接使用行数据
      if (row.title) {
        this.form = {
          id: row.id || '',
          title: row.title || '',
          project_id: this.projectId || row.project_id || '',
          sort: row.sort !== undefined && row.sort !== null ? Number(row.sort) : 0
        };
        this.dialogVisible = true;
      } else {
        // 调用详情接口获取完整信息
        collectionApi.categoryDetail({ id: row.id }).then((res) => {
          if (res && res.message) {
            _this.form = {
              id: res.message.id || '',
              title: res.message.title || '',
              project_id: _this.projectId || res.message.project_id || '',
              sort: res.message.sort !== undefined && res.message.sort !== null ? Number(res.message.sort) : 0
            };
            _this.dialogVisible = true;
          } else {
            _this.$message.error('获取详情失败');
          }
        }).catch((error) => {
          console.error('获取详情失败:', error);
          _this.$message.error('获取详情失败');
        });
      }
    },

    /** 删除类别 */
    handleDelete(row) {
      const _this = this;
      if (!row.id) {
        this.$message.warning('无法删除该数据');
        return;
      }
      
      this.$confirm('确定要删除该类别吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 构建删除参数，包含id和project_id
        const deleteData = {
          id: row.id,
          project_id: this.projectId || row.project_id || ''
        };
        
        // 调用删除API
        collectionApi.categoryDelete(deleteData).then((res) => {
          if (res) {
            _this.$message.success('删除成功');
            _this.getCategoryList();
          }
        }).catch((error) => {
          console.error('删除失败:', error);
          _this.$message.error('删除失败');
        });
      }).catch(() => {
        // 用户取消删除
      });
    },

    /** 提交表单 */
    submitForm() {
      const _this = this;
      this.$refs.dialogForm.validate((valid) => {
        if (valid) {
          this.is_ajax = true;
          
          // 构建提交数据
          const submitData = {
            project_id: this.form.project_id || this.projectId || '',
            title: this.form.title,
            sort: this.form.sort !== undefined && this.form.sort !== null ? Number(this.form.sort) : 0
          };
          
          // 如果是编辑，需要传id
          if (this.form.id) {
            submitData.id = this.form.id;
          }
          
          // 调用API创建或更新
          collectionApi.categoryCreateOrUpdate(submitData).then(function (res) {
            if (res) {
              _this.$message.success(_this.form.id ? '修改成功' : '添加成功');
              _this.dialogVisible = false;
              _this.getCategoryList();
            }
            _this.is_ajax = false;
          }).catch(function (error) {
            console.error('提交失败:', error);
            _this.$message.error('提交失败');
            _this.is_ajax = false;
          });
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },

    /** 重置表单 */
    resetForm() {
      if (this.$refs.dialogForm) {
        this.$refs.dialogForm.clearValidate();
      }
    },

    /** 对话框关闭后的回调 */
    handleDialogClosed() {
      this.resetForm();
      this.form = {
        id: '',
        title: '',
        project_id: this.projectId || '',
        sort: 0
      };
    }
  }
}
</script>

<style scoped>
.tab_content {
  min-height: 300px;
}

.form-hint {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style>

